/* eslint-disable consistent-return */
/* eslint-disable array-callback-return */
import React, { PureComponent } from 'react';
import { connect } from 'dva';
import { DownloadOutlined, QuestionCircleOutlined } from '@ant-design/icons';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { Row, Col, Card, Button, Input, Divider, Modal } from 'antd';
import router from 'umi/router';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import StandardTable from '@/components/StandardTable';
import Customer from '../../components/Customer';
import TextOverFlow from '../../components/TextOverFlow';
import Authorized from '@/utils/Authorized';
import downloadFile from '@/utils/utils';
import styles from '@/utils/utils.less';

const FormItem = Form.Item;
@connect(({ custinfo, loading }) => ({
  pageData: custinfo.pageData,
  loading: loading.models.custinfo,
  formFieldsValue: custinfo.formFieldsValue,
  valuesArr: custinfo.valuesArr,
}))
@Form.create()
class TableList extends PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      formValues: {},
      selectedRows: [],
      selectedRowKeys: [],
      INDST_CODE: [],
      CORP_NATURE: [],
    };

    this.formItemLayout = {
      labelCol: { md: { span: 10 } },
      wrapperCol: { md: { span: 14 } },
    };
  }

  componentDidMount() {
    const {
      dispatch,
    } = this.props;
    // 获取页面的所有字典值
    dispatch({
      type: 'publicdata/fetchDictCode',
      payload: ['INDST_CODE', 'CORP_NATURE'],
    }).then(data => {
      if (data && data.INDST_CODE && data.INDST_CODE.length) {
        this.setState({ INDST_CODE: data.INDST_CODE });
      }
      if (data && data.CORP_NATURE && data.CORP_NATURE.length) {
        this.setState({ CORP_NATURE: data.CORP_NATURE });
      }
    });
    this.getInitialList();
  }

  getInitialList = () => {
    const {
      pageData: { pagination },
      dispatch,
      location,
      formFieldsValue,
    } = this.props;
    if (location.queryParam) {
      dispatch({
        type: 'custinfo/updateModalData',
        payload: { formFieldsValue: location.queryParam },
      });
    }
    this.searchList(
      this.processFormData({ ...formFieldsValue }),
      pagination.current,
      pagination.pageSize
    );
  };

  // 点击查询按钮
  searchBtnList = () => {
    const { form, valuesArr, dispatch } = this.props;
    form.validateFieldsAndScroll([...valuesArr], (err, values) => {
      if (!err) {
        dispatch({
          type: 'custinfo/updateModalData',
          payload: {
            formFieldsValue: values,
          },
        });
        this.searchList(this.processFormData(values));
      }
    });
  };

  // 查询
  searchList = (
    formFieldsValue,
    currentPage = 1,
    pageSize = 10,
    isClear = true
  ) => {
    const { dispatch } = this.props;
    if (isClear) {
      this.setState({ selectedRows: [], selectedRowKeys: [] });
    }
    const pagerArg = { currentPage, pageSize };
    const values = {
      ...formFieldsValue,
      pagerArg,
    };

    dispatch({
      type: 'custinfo/updateModalData',
      payload: {
        values,
      },
    });

    dispatch({
      type: 'custinfo/fetchList',
      payload: {
        ...values,
      },
    });

    this.setState({
      formValues: values,
    });
  };

  // 处理form数据
  processFormData = fieldsValue => {
    const formFieldsValue = {};
    const tempFieldsValue = fieldsValue;
    Object.keys(tempFieldsValue).forEach(key => {
      if (key === 'uniCreditCode') {
        tempFieldsValue[key] = (tempFieldsValue[key] && tempFieldsValue[key].trim()) || null;
      }
      if (tempFieldsValue[key] && tempFieldsValue[key].key) {
        formFieldsValue[key] = tempFieldsValue[key].key === undefined ? null : tempFieldsValue[key].key;
      } else {
        formFieldsValue[key] = tempFieldsValue[key] === undefined ? null : tempFieldsValue[key];
      }
    });
    return formFieldsValue;
  };

  // 问题人员导出数据
  export = () => {
    const { selectedRowKeys } = this.state;
    if (!selectedRowKeys.length) {
      Modal.confirm({
        icon: <QuestionCircleOutlined />,
        title: '温馨提示',
        content: '如果不选择列表数据，则默认导出当前条件下所有数据',
        okText: '导出',
        cancelText: '取消',
        onOk: () => {
          this.exportExcel();
        },
      });
    } else {
      this.exportExcel();
    }
  };

  // 导出excel
  exportExcel = () => {
    const { selectedRowKeys, formValues } = this.state;
    const params = {
      mdCustIds: selectedRowKeys,
      ...formValues,
    };
    delete formValues.pagerArg;
    downloadFile(params, '/mgrApi/mgrMdCust/exportMdCustInfo', 'POST');
  };

  // 查看详情
  toDetail = mdCustId => {
    router.push(`/maindatamanage/custinfo/detail?custId=${mdCustId}`);
  };

  // 修改信息:客户信息
  updateInfo = mdCustId => {
    router.push(`/maindatamanage/custinfo/update?custId=${mdCustId}`);
  };

  // 点击复选框
  handleSelectRows = (selectedRows, selectedRowKeys) => {
    this.setState({ selectedRows, selectedRowKeys });
  };

  // 表格有变化：比如：切换页码
  handleStandardTableChange = pagination => {
    const { formFieldsValue } = this.props;
    this.searchList(
      this.processFormData(formFieldsValue),
      pagination.current,
      pagination.pageSize,
      false
    );
  };

  // 重置
  resetSearch = () => {
    const { form, dispatch } = this.props;
    dispatch({
      type: 'custinfo/updateModalData',
      payload: { formFieldsValue: {} },
    });
    form.resetFields();
  };

  render() {
    const {
      pageData,
      loading,
      form: { getFieldDecorator },
      formFieldsValue,
    } = this.props;
    const { selectedRows, selectedRowKeys, CORP_NATURE, INDST_CODE } = this.state;
    const renderSimpleForm = (
      <Form layout="inline">
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
          <Col md={8} sm={24}>
            <FormItem label="统一社会信用代码" {...this.formItemLayout}>
              {getFieldDecorator('uniCreditCode', {
                rules: [{ message: '请输入', required: false }],
                initialValue: formFieldsValue.uniCreditCode,
              })(<Input placeholder="请输入" maxLength={25} />)}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <FormItem label="客户名称" {...this.formItemLayout}>
              {getFieldDecorator('mdCustId', {
                rules: [{ message: '请选择' }],
                initialValue: formFieldsValue.mdCustId,
              })(<Customer attr allowClear />)}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <span className={styles.submitButtons}>
              <Button type="primary" onClick={this.searchBtnList}>
                查询
              </Button>
              <Button style={{ marginLeft: 8 }} onClick={this.resetSearch}>
                重置
              </Button>
            </span>
          </Col>
        </Row>
      </Form>
    );
    const columns = [
      {
        title: '客户编号',
        dataIndex: 'no',
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
      },
      {
        title: '统一社会信用代码',
        dataIndex: 'uniCreditCode',
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
      },
      {
        title: '客户名称',
        dataIndex: 'name',
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
        render: text => <TextOverFlow text={text} />,
      },
      {
        title: '公司类型',
        dataIndex: 'corpNature',
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
        render: text =>
          CORP_NATURE.map(item => {
            if (Number(item.itemCode) === text) {
              return item.itemName;
            }
          }),
      },
      {
        title: '行业分类',
        dataIndex: 'industryCode',
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
        render: text =>
          INDST_CODE.map(item => {
            if (Number(item.itemCode) === text) {
              return item.itemName;
            }
          }),
      },
      {
        title: '操作',
        dataIndex: 'operation',
        onHeaderCell: () => ({ style: { fontWeight: 'bold', width: 150, textAlign: 'center' } }),
        onCell: () => ({ style: { textAlign: 'center' } }),
        render: (text, record) => (
          <span>
            <a onClick={() => this.toDetail(record.mdCustId)}>查看</a>
            <Authorized authority="mgr:mgrMdCust:updataMdCustInfo" noMatch={null}>
              <Divider type="vertical" />
              <a onClick={() => this.updateInfo(record.mdCustId)}>修改</a>
            </Authorized>
          </span>
        ),
      },
    ];
    return (
      <PageHeaderWrapper>
        <Card className={styles.searchCard}>
          <div className={styles.tableListForm}>{renderSimpleForm}</div>
        </Card>
        <Card className={styles.tableCard}>
          <Row style={{ marginBottom: '16px' }}>
            <Authorized authority="mgr:mgrMdCust:exportMdCustInfo" noMatch={null}>
              <Button icon={<DownloadOutlined />} type="primary" onClick={this.export}>
                导出
              </Button>
            </Authorized>
          </Row>
          <StandardTable
            selectedRows={selectedRows}
            selectedRowKeys={selectedRowKeys}
            loading={loading}
            data={pageData}
            rowKey="mdCustId"
            columns={columns}
            onSelectRow={this.handleSelectRows}
            onChange={this.handleStandardTableChange}
          />
        </Card>
      </PageHeaderWrapper>
    );
  }
}

export default TableList;
